//
//  RootViewController.m
//  FGallery
//
//  Created by Grant Davis on 1/6/11.
//  Copyright 2011 Grant Davis Interactive, LLC. All rights reserved.
//

#import "PhotoBookViewController.h"
#import "WebRequest.h"
#import "WebConnetionArray.h"
#import "WebConnection.h"

static WebConnectionArray *browseAlbumList_connection = nil;
static WebConnectionArray *albumModify_connection = nil;    

static BOOL isAnniversary = NO;

static int curIndex = 0;

@implementation PhotoBookViewController

@synthesize delegate;

@synthesize networkImages;

@synthesize imageURLArray;



#pragma mark - View lifecycle

-(id)initWithImages:(NSArray *)images{
    
    self.networkImages = [[NSMutableArray alloc]init];
    [self.networkImages addObjectsFromArray:images];
    
    curPage = 0;
    
    isAnniversary = NO;
    
    return self;
    
}


//大事件

- (id)initWithImages:(NSArray *)images caption:(NSArray *)caption  dateArray:(NSArray *)dates   page:(int)page localImageNum:(int)localImageNum{
    
    self.networkImages = [[NSMutableArray alloc]init];
    [self.networkImages addObjectsFromArray:images];
    
    networkCaptions = [[NSMutableArray alloc]init];
    [networkCaptions addObjectsFromArray:caption];
    
    dateArray = [[NSMutableArray alloc]init];
    [dateArray addObjectsFromArray:dates];
    
    curPage = page;
    
    localImageCount = localImageNum;
    
    isAnniversary = YES;
    
    return self;
    
    
}



//本地数据
- (id)initWithLocalImages:(NSArray *)images caption:(NSArray *)caption page:(int)page{
    
    
    localImages  = [[NSMutableArray alloc]init];
    [localImages addObjectsFromArray:images];
    localCaptions = caption;
    curPage = page;
    isLocalImage = YES;
    
    isAnniversary = NO;
    
    return self;

    
    
}


- (void)loadView {
	[super loadView];
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    [self loadBrowseView];
    
   
    
}


#pragma mark -
#pragma mark Load View
- (void)loadBrowseView
{
    UIImage *captionIcon = [UIImage imageNamed:@"write_photo_iphone.png"];
    
    UIBarButtonItem *editCaptionButton = [[[UIBarButtonItem alloc] initWithImage:captionIcon style:UIBarButtonItemStylePlain target:self action:@selector(handleEditCaptionButtonTouch:)] autorelease];
    NSArray *rightBarItems = [NSArray arrayWithObjects:editCaptionButton, nil];
    
    
    UIImage *sendBtnBackground = [[UIImage imageNamed:@"topbuttonBG_iphone.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIImage *selectedSendBtnBackground = [[UIImage imageNamed:@"topbuttonBG1_iphone.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 40, 30);
    leftButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    [leftButton setTitle:@"设为封面" forState:UIControlStateNormal];
    leftButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [leftButton.titleLabel setTextColor:[UIColor whiteColor]];
    [leftButton addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
    [leftButton setBackgroundImage:selectedSendBtnBackground forState:UIControlStateSelected];
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    
    
    NSArray *leftBarItems = [NSArray arrayWithObjects:leftButtonItem, nil];
    
    
//    browseGallery = [[FGalleryViewController alloc] initWithPhotoSource:self rightBarItems:rightBarItems leftBarItems:leftBarItems];
//    [self.navigationController pushViewController:browseGallery animated:YES];
//    [browseGallery release];
    
    
    //xiaoyan
    if (localImages == nil) {
        localImages = [[NSMutableArray alloc]init];
    }
    
    if (localImages.count>0) {
        
        CLog(@"local images %@", localImages);
       browseGallery = [[FGalleryViewController alloc] initWithPhotoSource:self rightBarItems:rightBarItems leftBarItems:leftBarItems];
        [self.navigationController pushViewController:browseGallery animated:YES];
        
        [browseGallery release];
    }
    else{
        
        
        if (imageURLArray == nil) {
            
            imageURLArray = [[NSMutableArray alloc] init];
            
        }
        else{
            
            [imageURLArray removeAllObjects];
        }
        
        for (int i = 0;i<networkImages.count ; i++) {
             
            if ( curIndex < localImageCount ) { //本地图
                 
               [imageURLArray addObject:[networkImages objectAtIndex:i]];
                
            }
            else{
                
                NSString *string=[NSString stringWithFormat:@"%@%@/%@/480x480",BASEURL,@"/commons/attachment/download",[networkImages objectAtIndex:i]];
                [imageURLArray addObject:string];
            }
          
            CLog(@"net image %@", [imageURLArray objectAtIndex:i]);
            
        }    
        
        if (isAnniversary) {
           
            browseGallery = [[FGalleryViewController alloc] initWithPhotoSource:self page:curPage rightBarItems:nil leftBarItems:nil];
            
        }
        else{
            
             browseGallery = [[FGalleryViewController alloc] initWithPhotoSource:self page:curPage rightBarItems:rightBarItems leftBarItems:leftBarItems];
        }
       
        [self.navigationController pushViewController:browseGallery animated:YES];
        
        [browseGallery release];
    }

    
}


#pragma mark - FGalleryViewControllerDelegate Methods

- (NSString *)galleryPhotoCacheType
{
    
   if (localImages.count>0 ||  curIndex < localImageCount) {
        return kImageCache_Locale_Record;
    }
    else  {
        return kImageCache_Content_Browse; 
    }

   
}

- (int)numberOfPhotosForPhotoGallery:(FGalleryViewController *)gallery
{
    int num;
    if (localImages.count>0) {
        num = [localImages count];
    }
    else  {
        num = [networkImages count];
    }
	return num;
}


- (FGalleryPhotoSourceType)photoGallery:(FGalleryViewController *)gallery sourceTypeForPhotoAtIndex:(NSUInteger)index
{
    curIndex = index;

         
	 if (localImages.count>0 ) {
		return FGalleryPhotoSourceTypeLocal;
	}
         else {
             return FGalleryPhotoSourceTypeNetwork;
         }
}

- (NSString *)photoGallery:(FGalleryViewController *)gallery titleForPhotoAtIndex:(NSUInteger)index
{
    
    NSString *dateStr = nil;
    
    dateStr = [dateArray objectAtIndex:index];    
    
    if (dateStr != nil) {
        NSDate *zoneDate = [NSDate date];
        NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
        NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
        
        long long int dateTime;
        dateTime = [dateStr longLongValue];
        dateTime = dateTime/1000 +interval;
        
        NSDate *nd = [NSDate dateWithTimeIntervalSince1970:dateTime];
        NSString *createDateStr = [[PublicMethodEngine sharedPublicMethodEngine] NSDateToNSTring:nd];
        
        //int create_year = [[createDateStr substringWithRange: NSMakeRange(0, 4)] intValue];
        //int create_month=[[createDateStr substringWithRange: NSMakeRange(5, 2)] intValue];
        //int create_day=[[createDateStr substringWithRange: NSMakeRange(8, 2)] intValue];
        
        return [createDateStr substringToIndex:10];
    }
    else {
        return nil;
    }
    
    
}




- (NSString*)photoGallery:(FGalleryViewController *)gallery captionForPhotoAtIndex:(NSUInteger)index
{
    curIndex = index;
    
    NSString *caption = nil;
    if (localImages.count>0) {
        
        if (localCaptions == nil) {
            return @"";
        }
        caption = [localCaptions objectAtIndex:index];
        
    }
//    else if( gallery == networkGallery ) {
//        if (networkCaptions && index <[networkCaptions count]) {
//            caption = [networkCaptions objectAtIndex:index];
//        }
//        
//    }
    
    
    if (networkCaptions) {
        
         index = index%networkCaptions.count;
    
         caption = [networkCaptions objectAtIndex:index];
        
        PublicMethodEngine *methodEngine = [PublicMethodEngine sharedPublicMethodEngine];
       caption = [methodEngine changeStringFommat:caption];
        
    }
    else{
        
        caption = @"";
    }
    
    if ([caption isMemberOfClass:[NSNull class]]) {
        caption = @"";
    }
    
	return caption;
    
}


- (NSString*)photoGallery:(FGalleryViewController*)gallery filePathForPhotoSize:(FGalleryPhotoSize)size atIndex:(NSUInteger)index {
    return [localImages objectAtIndex:index];
}

- (NSString*)photoGallery:(FGalleryViewController *)gallery urlForPhotoSize:(FGalleryPhotoSize)size atIndex:(NSUInteger)index {
    
    curIndex = index;

    
    //xiaoyan
    index = index%imageURLArray.count;
    
    NSString *urlForPhoto = [NSString stringWithFormat:@"%@",[imageURLArray objectAtIndex:index]];
    
    return urlForPhoto;
}




#pragma mark - Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
    
    
}


- (void)dealloc {
  
    [localImages release];
    
    [networkImages release];
    [imageURLArray release];
   
    [networkCaptions release];
    [dateArray release];
    
    
    [containerBgView release];
    [containerView release];
    [textView release];
    
    [super dealloc];
}


@end

